package com.xzy.common.util;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xzy.xiao
 * @date 2023/4/4  17:14
 */
public class ThreadDataHolder {

    private static final InheritableThreadLocal<Map<Class<?>, Object>> THREAD_DATA_HOLDER = new InheritableThreadLocal<>();

    public static <T> void put(Class<T> clazz, T data) {
        Map<Class<?>, Object> classObjectMap = THREAD_DATA_HOLDER.get();
        if (classObjectMap == null) {
            classObjectMap = new LinkedHashMap<>();
            THREAD_DATA_HOLDER.set(classObjectMap);
        }

        classObjectMap.put(clazz, data);
    }

    public static <T> T get(Class<T> clazz) {
        Map<Class<?>, Object> classObjectMap = THREAD_DATA_HOLDER.get();
        if (classObjectMap == null) {
            return null;
        }

        return clazz.cast(classObjectMap.get(clazz));
    }

    public static void main(String[] args) {
        ThreadDataHolder.put(String.class, "666");
        ThreadDataHolder.put(Date.class, new Date());
        ThreadDataHolder.put(Long.class, 666L);


        System.out.println(ThreadDataHolder.get(String.class));
        System.out.println(ThreadDataHolder.get(Date.class));
        System.out.println(ThreadDataHolder.get(Long.class));
    }
}
